import time
from selenium import webdriver
from selenium.common import WebDriverException, NoSuchElementException
from selenium.webdriver.common.by import By


class Base:
    # 初始化打开浏览器
    def __init__(self, browser):
        if browser == 'chrome':
            self.driver = webdriver.Chrome()
            self.driver.maximize_window()
        elif browser == 'firefox':
            self.driver = webdriver.Firefox()
        elif browser == 'edge':
            self.driver = webdriver.Edge()
        else:
            print('不支持该浏览器')
            self.driver = None

    # 进入网页
    def get(self, url):
        try:
            self.driver.get(url)
        except WebDriverException:
            print('网址错误')

    # 浏览器后退
    def back(self):
        self.driver.back()

    # 浏览器前进
    def forward(self):
        self.driver.forward()

    # 浏览器刷新
    def refresh(self):
        self.driver.refresh()

    # 定位元素
    def find_element(self, locator):
        try:
            ele = self.driver.find_element(*locator)
            print(ele.get_attribute('outerHTML'))
            return ele
        except NoSuchElementException:
            print('元素定位失败')

    # 元素点击
    def click(self, locator):
        element = self.find_element(locator)
        if element is not None:
            element.click()
        else:
            print('元素没找到')

    # 元素输入
    def send_keys(self, locator, text):
        self.find_element(locator).send_keys(text)

    # 输入内容清空
    def clear(self, locator):
        self.find_element(locator).clear()

    # 获取元素属性
    def get_attribute(self, locator, attribute):
        self.find_element(locator).get_attribute(attribute)


    # 获取元素文本
    def get_text(self, locator):
        self.find_element(locator).text()

    # 退出浏览器
    def quit(self, seconds=3):
        time.sleep(seconds)
        self.driver.quit()


if __name__ == '__main__':
    base = Base('chrome')
    base.get('https://www.baidu.com')
    base.find_element((By.ID, 'kw'))
    base.get_attribute((By.ID, 'kw'))
    base.quit()
